<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="body">
      <div class="project">
        <el-form
          :model="basicForm"
          label-position="top"
          :rules="basicRules"
          ref="basicFormRef"
        >
          <!-- 孵化企业信息 -->
          <div class="project-part">
            <div class="project-part-title">企业信息</div>

            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item
                  label="企业名称"
                  prop="enterpriseName"
                >
                  <!-- <el-input
                    v-model="basicForm.enterpriseName"
                    placeholder="请输入企业名称"
                    :disabled="isDetail"
                  ></el-input> -->
                  <el-select
                    v-model="basicForm.enterpriseName"
                    :disabled="isDetail"
                    placeholder="请选择"
                    filterable
                    allow-create
                    default-first-option
                    @change="handleSelectChange"
                  >
                    <el-option
                      v-for="item in enterpriseOptions"
                      :key="item.socialCode"
                      :label="item.name"
                      :value="item.name"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <!-- <el-form-item label="年度" prop="year">
                  <el-select
                    placeholder="年度"
                    v-model="basicForm.year"
                    clearable
                    :disabled="isDetail"
                  >
                    <el-option
                      v-for="item in yearList"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item> -->
                <el-form-item
                  label="统一社会信用代码"
                  prop="socialCode"
                >
                  <el-input
                    v-model="basicForm.socialCode"
                    placeholder="请输入"
                    :disabled="isDetail || isExisting"
                  ></el-input>
                  <!-- <el-input
                    v-model="basicForm.socialCode"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input> -->
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="孵化时间">
                  <el-date-picker
                    v-model="basicForm.hatchTime"
                    type="date"
                    :disabled="isDetail"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="所属行业">
                  <el-input
                    v-model="basicForm.industryBelong"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="注册资本">
                  <el-input
                    v-model="basicForm.registeredCapital"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="融资状态">
                  <el-input
                    v-model="basicForm.financeStatus"
                    placeholder="请输入"
                    :disabled="isDetail"
                    type="textarea"
                    :rows="3"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="标志性产品">
                  <el-input
                    v-model="basicForm.signProduction"
                    placeholder="请输入"
                    :disabled="isDetail"
                    type="textarea"
                    :rows="3"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="成果转化营业收入(万元)"
                >
                  <el-input
                    v-model="basicForm.investment"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="预计孵化完成时间">
                  <el-date-picker
                    v-model="basicForm.planCompleteTime"
                    type="date"
                    :disabled="isDetail"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="孵化完成时间">
                  <el-date-picker
                    v-model="basicForm.completeTime"
                    type="date"
                    :disabled="isDetail"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="成果转化营业收入">
                  <el-input
                    v-model="basicForm.resultInvestment"
                    placeholder="请输入金额"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="联系人及方式">
                  <el-input
                    v-model="basicForm.contract"
                    placeholder="如李某某，13800138000"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="是否为规上企业">
                  <el-radio-group
                    v-model="basicForm.hasStandard"
                    :disabled="isDetail"
                  >
                    <el-radio label="是"></el-radio>
                    <el-radio label="否"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="是否为高新技术企业">
                  <el-radio-group
                    v-model="basicForm.hasTechnology"
                    :disabled="isDetail"
                  >
                    <el-radio label="是"></el-radio>
                    <el-radio label="否"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="是否为专精特新企业">
                  <el-radio-group
                    v-model="basicForm.hasMastery"
                    :disabled="isDetail"
                  >
                    <el-radio label="是"></el-radio>
                    <el-radio label="否"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col> -->
            </el-row>
          </div>
          <!-- 图片上传 -->
          <div class="project-part">
            <div class="project-part-title">企业图片</div>
            <el-form-item label="">
              <el-upload
                class="upload-image"
                action=""
                list-type="picture-card"
                :auto-upload="false"
                :on-change="handleChangeImage"
                :on-remove="handleRemoveImage"
                :on-preview="handlePreviewImage"
                :show-file-list="true"
                :file-list="fileList"
                v-if="!isDetail"
                multiple
                accept="image/*"
              >
                <i class="el-icon-plus"
                  ><div class="icon-text">上传图片</div></i
                >
                <div class="el-upload__tip" slot="tip">
                  支持格式: .jpg.png，单个文件不能超过5MB
                </div>
              </el-upload>

              <el-dialog
                :visible.sync="previewVisible"
                width="50%"
                v-if="!isDetail"
              >
                <img
                  :src="previewImage"
                  alt="预览"
                  style="width: 100%"
                />
              </el-dialog>
              <el-image
                v-for="item in fileList"
                :preview-src-list="previewImageList"
                v-if="isDetail"
                :key="item.url"
                :src="item.url"
                class="image"
              >
              </el-image>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import {
  addIncubateEnterprise,
  enterpriseInfoQuery,
  uploadFileById
} from '@/api/dataManagement'
import { STATIC_FILE_URL } from '@/api/config.js'
import dayjs from 'dayjs'

export default {
  components: {
    Breadcrumb
  },
  data() {
    return {
      basicForm: {
        pkid: '',
        year: '',
        enterpriseName: '',
        socialCode: '',
        hatchTime: '',
        industryBelong: '',
        registeredCapital: '',
        financeStatus: '',
        investment: '',
        signProduction: '',
        picture: ''
      },
      basicRules: {
        year: [
          {
            required: true,
            message: '请选择年度',
            trigger: 'blur'
          }
        ],
        enterpriseName: [
          {
            required: true,
            message: '请输入企业名称',
            trigger: 'blur'
          }
        ],
        socialCode: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      yearList: [],
      uploadFileList: [],
      previewImage: '',
      previewVisible: false,
      previewImageList: [],
      fileList: [],
      enterpriseOptions: [],
      isExisting: false
    }
  },
  computed: {
    titles() {
      return [this.$route.query.title || '孵化企业']
    },
    pkid() {
      return this.$route.query.pkid
    },
    isEdit() {
      return this.$route.query.isEdit === 'true'
    },
    isDetail() {
      return this.$route.query.isDetail === 'true'
    }
  },
  watch: {},
  mounted() {
    const year = new Date().getFullYear()
    this.yearList = [year, year - 1, year + 1]

    this.getEnterpriseOptions()

    if (this.pkid) {
      const data = JSON.parse(this.$route.query.data)
      this.basicForm = JSON.parse(JSON.stringify(data))
      this.basicForm.hatchTime = new Date(
        this.basicForm.hatchTime
      )

      // Convert date strings to Date objects for date pickers
      // if (this.basicForm.planCompleteTime) {
      //   this.basicForm.planCompleteTime = new Date(
      //     this.basicForm.planCompleteTime
      //   )
      // }
      // if (this.basicForm.completeTime) {
      //   this.basicForm.completeTime = new Date(
      //     this.basicForm.completeTime
      //   )
      // }

      // Initialize image files
      if (
        data.resourceFileInfos &&
        data.resourceFileInfos.length
      ) {
        this.fileList = data.resourceFileInfos.map(
          (item) => {
            return {
              ...item,
              url: `${STATIC_FILE_URL}${item.filePath}`
            }
          }
        )

        if (this.isDetail) {
          this.previewImageList = this.fileList.map(
            (item) => item.url
          )
        }

        this.uploadFileList = JSON.parse(
          JSON.stringify(this.fileList)
        )
      }
    }
  },
  methods: {
    handleSelectChange(value) {
      // 选择现有企业
      const enterpriseInfo = this.enterpriseOptions.find(
        (item) => item.name === value
      )
      this.isExisting = !!enterpriseInfo

      if (!enterpriseInfo) {
        this.basicForm.enterpriseName = value
        this.basicForm.socialCode = ''
        this.basicForm.enterpriseId = ''
      } else {
        this.basicForm.socialCode =
          enterpriseInfo.socialCode
        this.basicForm.enterpriseName = enterpriseInfo.name
        this.basicForm.enterpriseId = enterpriseInfo.pkid
      }
    },
    getEnterpriseOptions() {
      enterpriseInfoQuery({
        pageIndex: 1,
        pageSize: 999
      }).then((res) => {
        if (res.success) {
          this.enterpriseOptions = res.data.list
          this.isExisting = this.enterpriseOptions.some(
            (item) =>
              item.name === this.basicForm.enterpriseName
          )
        }
      })
    },
    saveInfo() {
      this.$refs.basicFormRef.validate((res) => {
        if (res) {
          const submitData = { ...this.basicForm }

          // Format dates
          if (submitData.planCompleteTime) {
            submitData.planCompleteTime = dayjs(
              submitData.planCompleteTime
            ).format('YYYY-MM-DD')
          } else {
            submitData.planCompleteTime = ''
          }

          if (submitData.completeTime) {
            submitData.completeTime = dayjs(
              submitData.completeTime
            ).format('YYYY-MM-DD')
          } else {
            submitData.completeTime = ''
          }

          this.loading = true

          // Handle image uploads
          const currentUpload = this.uploadFileList.filter(
            (i) => !i.pkid
          )
          const isUploadImage = this.uploadFileList
            .filter((i) => i.pkid)
            .map((item) => item.pkid)

          const uploadPromises = currentUpload.map(
            (file) => {
              const image = new FormData()
              image.append('file', file)
              return uploadFileById(image)
            }
          )

          Promise.all(uploadPromises)
            .then((results) => {
              const allSuccess = results.every(
                (res) => res.success
              )

              if (results.length > 0 && !allSuccess) {
                this.$message.error(
                  'Some images failed to upload'
                )
                this.loading = false
                return
              }

              let imageArr = results.map(
                (item) => item.data
              )
              submitData.picture = imageArr
                .concat(isUploadImage)
                .join(',')

              return addIncubateEnterprise(submitData)
            })
            .then((res) => {
              if (res && res.success) {
                this.$message.success(
                  this.pkid
                    ? 'Edit successful'
                    : 'Save successful'
                )
                this.$router.push({
                  path: '/dataManagement/technologyManagement/incubateEnterprises/list',
                  query: { refresh: Date.now() }
                })
              } else if (res) {
                this.$message.error(res.message)
              }
            })
            .catch((err) => {
              this.$message.error('Upload failed')
              console.error(err)
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    handleRemoveImage(file) {
      file.name
        ? (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.name !== file.name
          ))
        : (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.url !== file.url
          ))
    },

    handleChangeImage(file) {
      this.uploadFileList.push(file.raw)
    },

    handlePreviewImage(file) {
      if (file.url) {
        this.previewImage = file.url
      } else if (file.raw) {
        this.previewImage = URL.createObjectURL(file.raw)
      }
      this.previewVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .body {
    padding: 10px 0 0 20px;

    .top {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      padding-right: 10px;
    }
  }

  .line {
    display: flex;
    justify-content: center;
  }

  .el-icon-plus {
    margin-top: 50px;
    .icon-text {
      color: #999;
      font-size: 16px;
      margin-top: 10px;
    }
  }
}

::v-deep .el-upload-list__item-status-label {
  display: none !important;
}

.image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
}
</style>
